package com.test.common;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;



@ManagedBean(name="language")
@SessionScoped
public class LanguageBean implements Serializable{

	private static final long serialVersionUID = 1L;
	private String localeCode;
	
	private static Map<String,Object> countries;
	static {
		updateCountriesMap();
	}
	private static void updateCountriesMap() {
		countries=new LinkedHashMap<String,Object>();
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Locale locale = facesContext.getViewRoot().getLocale();
		ResourceBundle rb = ResourceBundle.getBundle("prop.messages", locale);
	
		countries.put(rb.getString("english"), Locale.ENGLISH);
		countries.put(rb.getString("german"), Locale.GERMAN);
	}
	
	
	public Map<String,Object> getCountriesInMap(){
		return countries;
	}
	
	public String getLocaleCode(){
		return localeCode;
	}
	
	public void setLocaleCode(String localeCode){
		this.localeCode=localeCode;
	}
	
	public void countryLocaleCodeChanged(ValueChangeEvent e){
		String newLocaleCode=e.getNewValue().toString();
		for (Map.Entry<String, Object> entry : countries.entrySet()){
			if (entry.getValue().toString().equals(newLocaleCode))
			FacesContext.getCurrentInstance().getViewRoot().setLocale((Locale)entry.getValue());
			
		}
		updateCountriesMap();
	}

}
